package com.stone.tool.pdf;

import com.alibaba.fastjson.JSON;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

import java.io.IOException;

/**
 * itextpdf
 *
 * @author stone
 * @date 2025/7/18 22:27
 */
public class PdfUtil {

    public static void main(String[] args) throws IOException {
        String filePath = "C:\\Users\\stone\\Desktop\\aaa.pdf";

        String contactNum = "合同编号：";
        String idCard = "身份证号：";
        String contactNumStr = extractTextAfterKeyword(filePath, contactNum);
        String idCardStr = extractTextAfterKeyword(filePath, idCard);
        System.out.println(contactNumStr + "=" + idCardStr);
    }

    /**
     * 提取PDF中特定关键词后面的内容
     *
     * @param filePath PDF文件路径
     * @param keyword  要查找的关键词
     * @return 关键词后面的内容
     */
    public static String extractTextAfterKeyword(String filePath, String keyword) throws IOException {
        PdfReader reader = new PdfReader(filePath);
        System.out.println(JSON.toJSONString(reader));
        System.out.println("=============");
        System.out.println(JSON.toJSONString(reader.getAcroForm()));
        System.out.println("=============");
        System.out.println(JSON.toJSONString(reader.getAcroFields().getXfa()));
        StringBuilder result = new StringBuilder();
        try {
            // 遍历所有页面
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                TextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                String pageText = PdfTextExtractor.getTextFromPage(reader, i, strategy);
                System.out.println(pageText);
                System.out.println("===========================");

                int index = pageText.indexOf(keyword);
//                if (index != -1) {
//                    // 找到关键词，提取后面的内容
//                    String textAfterKeyword = pageText.substring(index + keyword.length()).trim();
//                    result.append(textAfterKeyword);
//                    // 如果只需要第一个匹配项，可以去掉下面的break
//                    break;
//                }
            }
            return result.length() > 0 ? result.toString() : "未找到关键词: " + keyword;
        } finally {
            reader.close();
        }
    }

    /**
     * 使用正则表达式提取特定模式后的内容
     *
     * @param filePath PDF文件路径
     * @param regex    正则表达式
     * @return 匹配的内容
     */
    public String extractWithRegex(String filePath, String regex) throws IOException {
        PdfReader reader = new PdfReader(filePath);
        StringBuilder allText = new StringBuilder();

        try {
            // 提取所有文本
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                TextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                String pageText = PdfTextExtractor.getTextFromPage(reader, i, strategy);
                allText.append(pageText);
            }

            // 使用正则匹配
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
            java.util.regex.Matcher matcher = pattern.matcher(allText.toString());

            if (matcher.find()) {
                return matcher.group(1); // 返回第一个捕获组
            }
            return "未找到匹配内容";
        } finally {
            reader.close();
        }
    }
}
